import { defineComponent, reactive, onMounted, onUnmounted, watch, getCurrentInstance } from 'vue'
import Draw from './drawY'
import axios from 'axios'

export default defineComponent({
  components: {
    Draw
  },
  setup() {
    const instance = getCurrentInstance()
    const cdata = reactive({
      category: [],
      barData: [],
      rateData: []
    });
    let intervalId: number | null = null;

    // 获取路由参数
    const getSecondColumnValues = () => {
      return instance?.proxy?.$route.query.secondColumnValues as string || ''
    }

    // 请求数据
    const fetchData = async () => {
      try {
        const params = {
          IIIDataType: getSecondColumnValues(), // 使用secondColumnValues作为IIIDataType参数值
          flag: 2
        }
        const response = await axios.get(
          window.globalConfig.baseApi +'/api/Nurse/GetAllStatisticsDataGroupJson',
          { params }
        );
        
        const apiData = response.data || []
        
        // 解析数据并映射到图表所需格式
        cdata.category = apiData.map((item: any) => item.date) // 提取科室名称
        cdata.barData = apiData.map((item: any) => item.number)     // 也可根据需求设置为其他值
        setData();
      } catch (error) {
        console.error('折线图Y数据请求失败:', error);
      }
    };

    const setData = () => {
      cdata.rateData = []
      for (let i = 0; i < cdata.barData.length - 1; i++) {
        const rate = cdata.barData[i];
        cdata.rateData.push(rate.toFixed(2));
      }
    }

    // 监听参数变化
    watch(
      () => getSecondColumnValues(),
      () => {
        fetchData()
      }
    )

    const startTimer = () => {
      fetchData();
      intervalId = window.setInterval(fetchData, 300 * 1000);
    };

    const stopTimer = () => {
      if (intervalId !== null) {
        clearInterval(intervalId);
        intervalId = null;
      }
    };

    onMounted(() => {
      startTimer()
    })

    onUnmounted(() => {
      stopTimer();
    });

    return () => {
      return <div>
        <Draw cdata={cdata} />
      </div>
    }
  }
})